//
//  BDGanziTypeViewController.m
//  BeidouMall
//
//  Created by qie on 16/7/5.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDGanziTypeViewController.h"
#import "BDGanziTypeHeaderView.h"
#import "BDGanziSearchViewController.h"

#define scrollViewWidth [UIScreen mainScreen].bounds.size.width / 4
#define kButtonHeight 40.0

@interface BDGanziTypeViewController () <BDGanziTypeHeaderViewDelegate,
                                         SimplePopupViewDelegate,
                                         UITextFieldDelegate>
{
    NSInteger _selectIndex;// 选择了哪个一级分类(滑动控件上面的分类)
    NSDictionary *_imageDic;// 通过中文名称查找图片的名字
    BDGanziTypeHeaderView *_typeHeaderView;
    CGFloat _buttonWidth;
    SimplePopupView *_popView;
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线
    
    NSDictionary *_tanslateDic;// 通过中文名称换为英文名称,因为国际化不支持中文作为key
    NSDictionary *_titleDic;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *colletcionView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewBottomSpace;

@end

@implementation BDGanziTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _imageDic = @{@"便民":@"conveniency",@"民族特色":@"specialty",@"文化":@"culture",@"季产":@"season",
                  @"奢侈礼品":@"luxury",@"其他":@"other",@"民贸超市":@"privatelyCompany",@"糕点":@"pastry",
                  @"凉卤":@"cold_dish",@"食品":@"food",@"药材":@"medicinal",@"服饰":@"costume",
                  @"手工艺":@"handicraft",@"图书":@"book",@"生鲜":@"fresh",@"干货":@"dry_good",
                  @"非物质文化遗产":@"intangible_cultural",@"菌类":@"fungus",@"肉类":@"meat",@"保健品":@"health_food",
                  @"冷冻生鲜":@"freeze_food",@"干货":@"dry_good",@"特色饮品":@"beverage",@"包类":@"bag",
                  @"鞋服":@"clothes",@"首饰":@"jewelry",@"配件":@"parts",@"户外":@"outdoors",
                  @"生活":@"life",@"其他":@"other",@"食品":@"food",@"土特产":@"local_specialty",
                  @"百货":@"general_merchandise",@"针织品":@"hosiery",@"日常洗化":@"washing",@"季节商品":@"seasonal_merchandise",
                  @"烟酒茶":@"c_w_t",@"奶饮":@"milk_tea",@"方便食品":@"fast_food",@"休闲食品":@"leisure_food",
                  @"进口食品":@"import_food",@"米面调味":@"r_n_c",@"冷冻冷藏":@"freeze",@"纸制品":@"paper_product",
                  @"厨具用品":@"kitchen_ware",@"家电":@"household_appliances",@"家居用品":@"household_articles",@"文化用品":@"stationery_commodity",
                  @"毛巾":@"towel",@"内衣内裤":@"underwear_briefs",@"袜子":@"sock",@"床上用品":@"bedding_article",
                  @"个人护理":@"personal_care",@"家居清洁":@"household_clean",@"护肤品":@"skincare",@"美发护发":@"hairdressing",
                  @"口腔护理":@"mouth_care",
                  @"水果":@"fruit",@"蔬菜":@"vegetable",@"甜品":@"sweetmeat",
                  @"饮品":@"drink",@"简餐":@"simple_meal",@"鲜花":@"flower",
                  @"道具":@"prop"};
    
    _tanslateDic = @{@"民贸超市": @"Minmao company",@"糕点": @"Pastry",@"凉卤": @"Cold brine",
                     @"其他":  @"Others",@"食品":  @"Food",@"土特产": @"Local specialty",
                     @"百货": @"Department store",@"针织品": @"Knitwear",@"日常洗化": @"Cleaning products",
                     @"季节商品": @"Seasonal merchandise",@"烟酒茶": @"Tobacco and tea",
                     @"奶饮": @"Drink milk",@"休闲食品": @"Snacks",@"方便食品": @"instant food",
                     @"进口食品": @"Imported food",@"米面调味": @"Rice seasoning",@"冷冻冷藏": @"Cold storage",
                     @"纸制品": @"Paper Products",@"厨具用品": @"Kitchen utensils",@"家电": @"Household electrical",
                     @"家居用品": @"Home Furnishing",@"文化用品": @"Cultural products",@"毛巾": @"Towel",
                     @"内衣内裤": @"Underwear",@"袜子": @"Socks",@"床上用品": @"Bedding article",
                     @"家居清洁": @"Home cleaning",@"护肤品": @"Skin care",@"美发护发": @"Hair care",
                     @"口腔护理": @"Oral nursing",@"药材": @"Herbs",@"食品": @"Food",
                     @"服饰": @"Clothes",@"手工艺":  @"Handicraft",@"菌类": @"Fungus",
                     @"肉类":  @"Meats",@"保健品": @"Health products",@"冷冻生鲜":  @"Frozen fresh",
                     @"干货": @"Goods",@"特色饮品": @"Special drink",@"包类": @"Bags",
                     @"鞋服": @"Shoes & Clothing",@"首饰":  @"Jewelry",@"户外": @"Outdoors",
                     @"生活": @"Living",@"图书": @"Books",@"生鲜": @"Fresh",
                     @"奢侈礼品" : @"luxury",@"非物质文化遗产" : @"intangible_cultural",@"配件" : @"parts",
                     @"水果":@"fruit",@"蔬菜":@"vegetable",@"甜品":@"sweetmeat",
                     @"饮品":@"drink",@"简餐":@"simple_meal",@"鲜花":@"flower",
                     @"道具":@"prop",@"果蔬生鲜":@"fruit_vegetable",@"速食":@"fastfood",
                     @"派对":@"party"};
    
    _titleDic = @{@"便民服务":@"Convenience services",@"民族特色":@"National specialty"
                  ,@"文化产品":@"Cultural products title",@"季产":@"Season production"};
    
    [self setScrollViewType];// 构造一级滑动分类的控件,并且有初值(从分类进入时)
    [self setHeaderPopView];
    
    _selectIndex = 0;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavgationBarBlackLine];
    
    // nav_bg2一个透明的图片替换原来的nav_bg
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
    _typeHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BDGanziTypeHeader" owner:nil options:nil].firstObject;
    _typeHeaderView.frame = CGRectMake(0.0, 0.0, kScreen_Width, 64.0);
    _typeHeaderView.tag = 942;
    [self.navigationController.view addSubview:_typeHeaderView];
    _typeHeaderView.searchTextField.delegate = self;// 否则再次进入不响应代理方法
    _typeHeaderView.searchTextField.layer.cornerRadius = 5.0;
    _typeHeaderView.searchTextField.layer.masksToBounds = YES;
    _typeHeaderView.searchLabel.text = NSLocalizedString(@"Search store goods", nil);
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        _typeHeaderView.searchLabel.font = [UIFont fontWithName:@"Bzdbt" size:10.0];
    } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
        _typeHeaderView.searchLabel.font = [UIFont systemFontOfSize:15.0];
    } else {
        _typeHeaderView.searchLabel.font = [UIFont systemFontOfSize:15.0];
    }
    _typeHeaderView.delegate = self;
    [self dropShadowWithOffset:CGSizeMake(0, 0)
                        radius:2
                         color:[UIColor lightGrayColor]
                       opacity:0.8];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden = NO;
    if ([_typeHeaderView.searchTextField isFirstResponder]) {
        [_typeHeaderView.searchTextField resignFirstResponder];
    }
    if (_typeHeaderView) {
        [_typeHeaderView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark BDGanziTypeHeaderView delegate

- (void)backMethod {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)homeMethod:(UIButton *)sender {
    [_popView show];
}

- (void)simplePopupView:(SimplePopupView *)popView clickAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"代理方法，点击了第%ld行",(long)indexPath.row);
    if (indexPath.row == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } else if (indexPath.row == 1) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    }
}

#pragma mark Private method

- (void)setScrollViewType {
    _buttonWidth = kScreen_Width * 0.233;
    self.scrollViewWidthConstraint.constant = _buttonWidth;
    
    NSInteger index = 0;
    if (_firstArr.count == 0 && _secondArr.count == 0) {
        _firstArr = @[@"食品",@"服饰",@"药材",@"奢侈礼品",@"手工艺",@"其他"];
        _secondArr = @[@[@"菌类",@"肉类",@"保健品",@"冷冻生鲜",@"干货",@"特色饮品",@"其他"],
                       @[@"包类",@"鞋服",@"首饰",@"配件",@"户外",@"生活",@"其他"],
                       @[@"药材"],
                       @[@"非物质文化遗产",@"其他"],
                       @[@"手工艺"],
                       @[@"图书",@"生鲜",@"干货",@"其他"]];
        
    }
    
    _scrollView.contentSize = CGSizeMake(_buttonWidth, kButtonHeight * _firstArr.count);
    _scrollView.showsVerticalScrollIndicator = NO;
    for (NSString *title in _firstArr) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, kButtonHeight * index, _buttonWidth, kButtonHeight);
        [btn setTitle:NSLocalizedString(_tanslateDic[title], nil) forState:UIControlStateNormal];
        [btn setTitleColor:RGBColor(51, 51, 51) forState:UIControlStateNormal];
        if ([self.storeType isEqualToString:@"MINMAO_CHAIN"]) {
            [btn setTitleColor:RGBColor(25, 127, 228) forState:UIControlStateSelected];
        } else if ([self.storeType isEqualToString:@"HOLY_GARZE"]) {
            [btn setTitleColor:RGBColor(0, 162, 71) forState:UIControlStateSelected];
        } else {
            [btn setTitleColor:RGBColor(195, 3, 3) forState:UIControlStateSelected];
        }
        
        [btn addTarget:self action:@selector(firstButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
        index++;
        btn.tag = 100 + index;
        btn.selected = index == 1 ? YES : NO;
        if (index == 1) {
            [btn setBackgroundColor:RGBColor(238, 238, 238)];
        }
        [_scrollView addSubview:btn];
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
            btn.titleLabel.numberOfLines = 0;
            btn.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
        }
        if (index != _firstArr.count) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, kButtonHeight * index - 1, _buttonWidth, 1)];
            line.backgroundColor = RGBColor(238, 238, 238);
            [_scrollView addSubview:line];
        }
    }
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 3, kButtonHeight)];
    if ([self.storeType isEqualToString:@"MINMAO_CHAIN"]) {
        line.backgroundColor = RGBColor(25, 127, 228);
    } else if ([self.storeType isEqualToString:@"HOLY_GARZE"]) {
        line.backgroundColor = RGBColor(0, 162, 71);
    } else {
        line.backgroundColor = RGBColor(195, 3, 3);
    }
    
    line.tag = 998;
    [_scrollView addSubview:line];
}

- (void)firstButtonClick:(UIButton *)sender {// 一级分类按钮
    for (UIView *view in _scrollView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            btn.selected = NO;
            [btn setBackgroundColor:RGBColor(255, 255, 255)];
        }
        if (view.tag == 998) {
            [UIView beginAnimations:@"move" context:nil];
            view.center = sender.center;
            view.x = 0;
            [UIView commitAnimations];
        }
    }
    _selectIndex = sender.tag - 101;
    sender.selected = YES;
    [sender setBackgroundColor:RGBColor(238, 238, 238)];
    [self.colletcionView reloadData];
}

- (void)setHeaderPopView {
    NSArray *tmpArray = @[NSLocalizedString(@"home", nil),NSLocalizedString(@"message", nil)];
    NSArray *images = @[@"homeback",@"messageback"];
    //左
    _popView = [[SimplePopupView alloc] initWithFrame:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)
                                         andDirection:PopViewDirectionTop
                                            andTitles:tmpArray
                                            andImages:images
                                       trianglePecent:0.5]; //箭头位于popview中间0.5位置
    [self.navigationController.navigationBar showPopView:_popView AtPoint:CGPointMake(0.5, 0)];//箭头位于button的x=0.y=0.5比例处
    _popView.delegate = self; //需要正式使用时注意代理
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)dropShadowWithOffset:(CGSize)offset
                      radius:(CGFloat)radius
                       color:(UIColor *)color
                     opacity:(CGFloat)opacity {// 导航栏下边阴影
    
    // Creating shadow path for better performance
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.navigationController.navigationBar.bounds);
    self.navigationController.navigationBar.layer.shadowPath = path;
    CGPathCloseSubpath(path);
    CGPathRelease(path);
    
    self.navigationController.navigationBar.layer.shadowColor = color.CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = offset;
    self.navigationController.navigationBar.layer.shadowRadius = radius;
    self.navigationController.navigationBar.layer.shadowOpacity = opacity;
    
    // Default clipsToBounds is YES, will clip off the shadow, so we disable it.
    self.navigationController.navigationBar.clipsToBounds = NO;
    
}

#pragma mark - colletionView dataSrouce

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    NSString *reuseIdentifier;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        reuseIdentifier = @"collectionViewHeader";
    }
    
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuseIdentifier   forIndexPath:indexPath];
    
    UILabel *label = (UILabel *)[view viewWithTag:101];
    NSString *title = _firstArr[_selectIndex];
    if ([title isEqualToString:@"民贸超市"]) {// 民贸超市是二级分类,它的子分类 食品 土特产 百货等是三级分类
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
            NSString *key = _secondArr[0][indexPath.section];
            label.text = NSLocalizedString(_tanslateDic[key], nil);
            label.textColor = RGBColor(170, 170, 170);
        }
    } else {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
            NSString *key = _firstArr[_selectIndex];
            label.text = NSLocalizedString(_tanslateDic[key], nil);
            label.textColor = RGBColor(170, 170, 170);
        }
    }
    return view;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    NSString *title = _firstArr[_selectIndex];
    if ([title isEqualToString:@"民贸超市"]) {
        NSArray *arr = _secondArr[_selectIndex];// 这是三级分类
        return arr.count;
    }
    return 1.0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *arr = _secondArr[_selectIndex];
    return arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = _firstArr[_selectIndex];
    NSString *innerTitle;
    if ([title isEqualToString:@"民贸超市"]) {
        innerTitle = @"";
    } else {
        innerTitle = _secondArr[_selectIndex][indexPath.row];
    }
    if ([innerTitle isEqualToString:@"其他"]) {// 除民贸超市外的其他类别选用otherType样式
        static NSString *cellStr = @"otherTypeCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        
        UILabel *label = (UILabel *)[cell viewWithTag:102];
        label.text = NSLocalizedString(_tanslateDic[@"其他"], nil);
        label.font = [UIFont systemFontOfSize:11.0];
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
            label.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
            label.numberOfLines = 0;
        }
        return cell;
    } else {
        static NSString *cellStr = @"typeCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
        
        NSString *key;
        NSString *imageName;
        NSString *name;
        
        key = _secondArr[_selectIndex][indexPath.row];
        imageName = _imageDic[key];
        name = _secondArr[_selectIndex][indexPath.row];
        
        if ([UIImage imageNamed:imageName]) {
            imageView.image = [UIImage imageNamed:imageName];
            if ([imageName isEqualToString:@"freeze_food"]) {// update by wyp 2016-06-12 所有鸡翅图片改为鱼图片,因为不好找所以都改了
                imageView.image = [UIImage imageNamed:@"freeze"];
            }
            if ([name isEqualToString:@"冷冻冷藏"]) {// update by wyp 2016-06-14 冷冻冷藏改为鸡翅图片
                imageView.image = [UIImage imageNamed:@"freeze_food"];
            }
        } else {
            imageView.image = [UIImage imageNamed:@"image_empty"];
        }
        
        UILabel *label = (UILabel *)[cell viewWithTag:102];
        label.text = NSLocalizedString(_tanslateDic[name], nil);
        label.font = [UIFont systemFontOfSize:9.0];
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
            label.font = [UIFont fontWithName:@"Bzdbt" size:7.0];
            label.numberOfLines = 0;
        }
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width,height;
    width = (kScreen_Width - _buttonWidth - 5.0) / 3.0;
    if (kScreen_Width <= 320.0) {
        height = width / 0.736;
    } else {
        width = width - 0.2;
        height = width / 0.736;
    }
    return (CGSize){width,height};
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziSearchViewController *searchVC = [stroyboard instantiateViewControllerWithIdentifier:@"ganziSearchStoryboardID"];
    searchVC.storeType = self.storeType;
    searchVC.secondTitle = _firstArr[_selectIndex];
    searchVC.thridTitle = _secondArr[_selectIndex][indexPath.row];
    
    if ([searchVC.secondTitle isEqualToString:@"奢侈礼品"]) {// 奢侈礼品是一级分类,所有级别上升一级
        searchVC.firstTitle = _firstArr[_selectIndex];
        searchVC.secondTitle = _secondArr[_selectIndex][indexPath.row];
        searchVC.thridTitle = _secondArr[_selectIndex][indexPath.row];
    }
    if ([searchVC.secondTitle isEqualToString:@"其他"] && searchVC.firstTitle == nil) {// 其他里面都是二级分类
        searchVC.secondTitle = _secondArr[_selectIndex][indexPath.row];
        searchVC.thridTitle = _secondArr[_selectIndex][indexPath.row];
        if ([searchVC.secondTitle isEqualToString:@"其他"]) {// 分类里面其他的其他要特殊标记
            searchVC.otherTitle = @"其他";
        }
    }
    
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziSearchViewController *searchVC = [stroyboard instantiateViewControllerWithIdentifier:@"ganziSearchStoryboardID"];
    searchVC.searchType = YES;
    searchVC.storeType = self.storeType;
    [self.navigationController pushViewController:searchVC animated:YES];
    
    return NO;
}

@end
